<template>
  <div>
    <table cellspacing>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="checkall" />
          </th>
          <th>商品名称</th>
          <th>商品图片</th>
          <th>商品价格</th>
          <th>商品数量</th>
          <th>商品总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody v-for="(item, index) in this.lists " :key="item.id">
        <tr>
          <td>
            <input type="checkbox" v-model="item.flag" />
          </td>
          <td>{{item.name}}</td>
          <td>
            <img :src="item.img" alt />
          </td>
          <td>{{item.price}}</td>
          <td>
            <button @click="jia(item)">+</button>
            {{item.num}}
            <button @click="jian(item)">-</button>
          </td>
          <td>{{item.price*item.num}}</td>
          <td>
            <button style="background-color:red;border:0;" @click="del(index)">删除</button>
          </td>
        </tr>
      </tbody>
      <p>总价格{{totalPrice}},商品总数量{{totalCount}}</p>
    </table>
  </div>
</template>

<script>
import list from "../../public/data";
export default {
  data() {
    return {
      lists: [],
    };
  },
  mounted() {
    this.getlist();
  },
  methods: {
    getlist() {
      //数据
      this.lists = list.flat();
      console.log(this.lists);
    },
    //删除
    del(index) {
      this.lists.splice(index, 1);
    },
    //加
    jia(item) {
      item.num++;
      //    item.stock=item.price*item.num
    },
    //减
    jian(item) {
      if (item.num != 0) {
        item.num--;
        // item.stock=item.price*item.num
      }
    },
  },
  computed: {
    // 全选反选
    checkall: {
      get() {
        return this.lists.every((item) => item.flag);
      },
      set(val) {
        this.lists.map((item) => (item.flag = val));
      },
    },
    // 总件数
    totalCount: function () {
      var totalCount = 0;
      for (var i = 0; i < this.lists.length; i++) {
        totalCount += this.lists[i].num;
      }
      return totalCount;
    },
    // 总价钱
    totalPrice: function () {
      var totalPrice = 0;
      for (var i = 0; i < this.lists.length; i++) {
        totalPrice += this.lists[i].price * this.lists[i].num;
      }
      return totalPrice;
    },
  },
};
</script>

<style scoped>
img {
  width: 60px;
  height: 60px;
}
input {
  text-align: center;
}
</style>